package org.onvivals.app.ai.asr;

import com.alibaba.nls.client.AccessToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class ApplicationService implements ApplicationListener<ContextRefreshedEvent> {

	@Autowired
	RedisTemplate<String, String> redisTemplate;

	public static ApplicationService application = null;

	@Value("${aliyun.nls.accessKeyId}")
	private String accessKeyId;
	@Value("${aliyun.nls.accessKeySecret}")
	private String accessKeySecret;
	@Value("${aliyun.nls.url}")
	private String url;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
		//启动客户端
		if (contextRefreshedEvent.getApplicationContext().getParent() == null) {
			log.info("客户端启动-------------------------->");
			synchronized (this) {
				ApplicationService.application = this;
				new NlsClientService(accessKeyId, accessKeySecret, url);
				log.info("阿里云 NlsClient 初始化完毕");
				AccessToken accessToken = NlsClientService.getAccessToken();
				redisTemplate.opsForValue().set("nlp:token", accessToken.getToken(), 6, TimeUnit.HOURS);
			}
		}
	}
}
